package services;

import tw.edu.tku.im.maze.DeliveryListenerI;
import tw.edu.tku.im.maze.RepPacket;
import tw.edu.tku.im.maze.RoomListDeliverer;
import tw.edu.tku.im.maze.RoomListReq;
import tw.edu.tku.im.maze.TimeOutRep;
import tw.edu.tku.im.maze.UpdateRoomDeliverer;
import tw.edu.tku.im.maze.UpdateRoomReq;

import com.example.maze.ConnectionInfo;

import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;

public class UpdateRoomStatusService extends IntentService 
                              implements DeliveryListenerI{

   //[ -------------------- constant --------------------
   public  static final String BROADCAST_ACTION= "UpdateRoomStatus";   
   private static final int    DELAY_TIME      = 2000;    // milli second
   //] -------------------- constant --------------------
   
   public UpdateRoomStatusService()            { super("UpdateRoomStatus"); }
   public UpdateRoomStatusService(String name) { super(name); }

   @Override
   protected void onHandleIntent(Intent intent) {
      //[ 斷線時 theUpdateService= null, 使重啟得以判定是否造新 Service      
      ConnectionInfo.theUpdateService= this;
      UpdateRoomDeliverer mUpdateRoomDeliverer= new UpdateRoomDeliverer();
      try{         
         while(ConnectionInfo.roomStatusupdateLoop == ConnectionInfo.CONTINUE) {
            mUpdateRoomDeliverer.deliver(new UpdateRoomReq(ConnectionInfo.roomId), this);            
            Thread.sleep(UpdateRoomStatusService.DELAY_TIME);            
            if(ConnectionInfo.roomStatusupdateLoop == ConnectionInfo.INTERRUPT) {           
               android.util.Log.d("DebugMsg", "INTERRUPT....");
               ConnectionInfo.theUpdateService= null;
            }
         }
      } catch(Exception e) {}
   }
   
   // --------------------------------------------------
   @Override
   public void processReply(RepPacket rep) { 
      if(rep instanceof TimeOutRep) {
         return; //: 直接重連即可
      } else {
         Intent localIntent= new Intent(BROADCAST_ACTION);
         localIntent.putExtra("packet", rep);
         LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
      }     
   }
   
   // --------------------------------------------------
}
